#include<stdio.h>
#include<stdlib.h>

/*
 * more01.c - version 0.2 of more
 */

#define PAGELEN 24
#define LINELEN 512

void do_more(FILE *);
int see_more(FILE *);

int main(int ac, char *av[])
{
    FILE *fp;

    // no args, read from stdin
    if( 1 == ac )
        do_more(stdin);
    else
    {
        while(--ac)
        {
            if( NULL != (fp = fopen(*++av, "r")) )
            {
                do_more(fp);
                fclose(fp);
            }
            else
                exit(1);
        }
    }

    return 0;
}

void do_more(FILE *fp)
{
    // 读取 PAGELEN 行，然后调用 see_more 显示
    char line[LINELEN];
    int num_of_lines = 0;
    int see_more(FILE *), reply;

    // read keyboard from tty file
    FILE *fp_tty;
    fp_tty = fopen("/dev/tty", "r");
    if(NULL == fp_tty)
        exit(1);

    // 从文件中读取LINELEN个字符到数组
    while(fgets(line, LINELEN, fp))
    {
        // 如果显示满屏了，调用 see_more 询问按键
        if(PAGELEN == num_of_lines)
        {
            reply = see_more(fp_tty);
            if(0 == reply)
                break;
            num_of_lines -= reply;
        }

        // 文件结尾退出
        if(EOF == fputs(line, stdout))
            exit(1);

        // 行数递增
        num_of_lines++;
    }
}

// 打印提示信息，等待用户按键
int see_more(FILE *cmd)
{
    int c;
    printf("\033[7m more?\033[m");

    // reads from tty
    while(EOF != (c = getc(cmd)))
    {
        if('q' == c)
            return 0;// quit
        if(' ' == c)
            return PAGELEN;// next page
        if('\n' == c)
            return 1;// next line
    }
    
    return 0;
}